package com.wwwarehouse.usercenter.fragment.invite;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ApkTools;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.adapter.InviteDetailsAdapter;
import com.wwwarehouse.usercenter.bean.response.InviteInfoResponseBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.wwwarehouse.usercenter.fragment.review.ReviewInviteeFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.wwwarehouse.usercenter.constant.UserCenterConstant.KEY_INVITE_CHECK_LIST;
import static com.wwwarehouse.usercenter.constant.UserCenterConstant.KEY_INVITE_CHECK_POSITION;
import static com.wwwarehouse.usercenter.fragment.invite.ShowInvitedFragment.KEY_INVITE_MOBILE;
import static com.wwwarehouse.usercenter.fragment.invite.ShowInvitedFragment.KEY_INVITE_NAME;
import static com.wwwarehouse.usercenter.fragment.invite.ShowInvitedFragment.KEY_INVITE_PAGE;
import static com.wwwarehouse.usercenter.fragment.invite.ShowInvitedFragment.KEY_INVITE_SORT;
import static com.wwwarehouse.usercenter.fragment.invite.ShowInvitedFragment.KEY_INVITE_STATUS;
import static com.wwwarehouse.usercenter.fragment.invite.ShowInvitedFragment.SIZE;

/**
 * Created by Jackie on 2017/8/17.
 * 查看邀请人
 */

public class InviteDetailsFragment extends BaseFragment implements EasyPopupWindow.ChildClickListener, View.OnClickListener {
    private View mRootView;
    private StateLayout mStateLayout;
    protected GridView mGridView;
    private InviteDetailsAdapter mAdapter;

    protected InviteInfoResponseBean.InviteDetailsBean mInviteDetailsBean;
    protected EasyPopupWindow mEasyPopupWindow;

    private List<InviteInfoResponseBean.InviteDetailsBean> mInviteRegisterList;     //已注册集合
    private List<InviteInfoResponseBean.InviteDetailsBean> mInviteCheckList;        //待审核集合
    private int mInviteCheckPosition;

    private String mMobile;
    private String mName;
    private Set<Integer> mStatusSet;
    private String mSort;
    private int mPage = 0;

    private static final int REQUEST_GET_INVITE_INFO = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_invite_details, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (enter) {
            getInviteInfo(mMobile, mName, mStatusSet, mPage, SIZE, mSort);
        }

        return null;
    }

    private void initView() {
        mStateLayout = findView(mRootView, R.id.sl_layout);
        mGridView = findView(mRootView, R.id.gv_details);

        Bundle bundle = getArguments();
        if (bundle != null) {
            mMobile = bundle.getString(KEY_INVITE_MOBILE);
            mName = bundle.getString(KEY_INVITE_NAME);
            mStatusSet = (Set<Integer>) bundle.getSerializable(KEY_INVITE_STATUS);
            mSort = bundle.getString(KEY_INVITE_SORT);
            mPage = bundle.getInt(KEY_INVITE_PAGE);
        }

        mInviteRegisterList = new ArrayList<>();
        mInviteCheckList = new ArrayList<>();
    }

    private void initEvent() {

    }

    @Override
    public void getChildView(int layoutId, View view) {
        Button call = findView(view, R.id.btn_call_phone);
        Button contact = findView(view, R.id.btn_wechat_contact);
        Button check = findView(view, R.id.btn_check_register);
        Button cancel = findView(view, R.id.btn_cancel);

        call.setOnClickListener(this);
        contact.setOnClickListener(this);

        if (check != null) {
            check.setOnClickListener(this);
        }

        cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_call_phone) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mInviteDetailsBean.getInviteeMobile()));
            startActivity(intent);
        } else if (id == R.id.btn_wechat_contact) {
            if (!ApkTools.isWeixinInstall(mActivity)) {
                toast(R.string.wechat_not_installed);
            } else {
                ApkTools.launchWechat(mActivity);
            }
        } else if (id == R.id.btn_check_register) {
            ReviewInviteeFragment reviewInviteeFragment = new ReviewInviteeFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable(KEY_INVITE_CHECK_LIST, (Serializable) mInviteCheckList);
            bundle.putInt(KEY_INVITE_CHECK_POSITION, mInviteCheckPosition);
            reviewInviteeFragment.setArguments(bundle);
            pushFragment(reviewInviteeFragment);
        } else if (id == R.id.btn_cancel) {

        }

        if (mEasyPopupWindow != null && mEasyPopupWindow.isShowing()) {
            mEasyPopupWindow.dismiss();
        }
    }

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }

    private void getInviteInfo(String mobile, String name, Set<Integer> statusSet, int page, int size, String sort) {
        mStateLayout.showProgressView(false);

        Map map = new HashMap();

        if (!TextUtils.isEmpty(mobile)) {
            map.put("inviteeMobile", mobile);
        }

        if (!TextUtils.isEmpty(name)) {
            map.put("inviteeName", name);
        }

        if (statusSet != null && statusSet.size() > 0) {
            map.put("inviteeList", statusSet);
        }

        map.put("page", page);
        map.put("size", size);
        map.put("sort", sort);

        NoHttpUtils.httpPost(UserCenterConstant.URL_GET_INVITE_INFO, map, mOnResponseListener, REQUEST_GET_INVITE_INFO);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_INVITE_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        InviteInfoResponseBean inviteInfoResponseBean = JSON.parseObject(commonClass.getData().toString(), InviteInfoResponseBean.class);
                        final List<InviteInfoResponseBean.InviteDetailsBean> inviteDetailsList = inviteInfoResponseBean.getList();

                        final ViewTreeObserver viewTreeObserver = mGridView.getViewTreeObserver();

                        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                            @Override
                            public void onGlobalLayout() {
                                viewTreeObserver.removeOnGlobalLayoutListener(this);

                                int itemHeight = (mGridView.getMeasuredHeight() - mGridView.getPaddingTop() - mGridView.getPaddingBottom() - mGridView.getVerticalSpacing() * (mGridView.getNumColumns() - 1)) / mGridView.getNumColumns();

                                mAdapter = new InviteDetailsAdapter(mActivity, inviteDetailsList, itemHeight);
                                mGridView.setAdapter(mAdapter);
                            }
                        });

                        adapterListener(inviteDetailsList);

                        // 过滤待审核列表
                        filterCheckList(inviteDetailsList);
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                getInviteInfo(mMobile, mName, mStatusSet, mPage, SIZE, mSort);
                            }
                        });
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mStateLayout.showNetworkView(false);
            mStateLayout.setNetworkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mStateLayout.showProgressView(false);

                    getInviteInfo(mMobile, mName, mStatusSet, mPage, SIZE, mSort);
                }
            });
        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();
        }
    };

    public void adapterListener(final List<InviteInfoResponseBean.InviteDetailsBean> inviteDetailList){
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mInviteDetailsBean = inviteDetailList.get(position);

                if (mInviteDetailsBean.getInviteeStatus().getInviteeStatusCode() == 0) {
                    //待审核
                    mInviteCheckPosition = getCurrentPositionInCheckList(mInviteDetailsBean);
                    mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.invite_to_be_check_popupwindow, mActivity, mActivity.findViewById(android.R.id.content), true, InviteDetailsFragment.this);
                } else {
                    mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.invite_has_checked_popupwindow, mActivity, mActivity.findViewById(android.R.id.content), true, InviteDetailsFragment.this);
                }
            }
        });
    }

    private int getCurrentPositionInCheckList(InviteInfoResponseBean.InviteDetailsBean inviteCheckBean) {
        for (int i = 0; i < mInviteCheckList.size(); i++) {
            InviteInfoResponseBean.InviteDetailsBean inviteDetailsBean = mInviteCheckList.get(i);

            if (inviteCheckBean == inviteDetailsBean) {
                return i;
            }
        }

        return 0;
    }

    private void filterCheckList(List<InviteInfoResponseBean.InviteDetailsBean> inviteDetailsList) {
        mInviteCheckList.clear();

        for (int i = 0; i < inviteDetailsList.size(); i++) {
            InviteInfoResponseBean.InviteDetailsBean inviteDetailsBean = inviteDetailsList.get(i);
            if (inviteDetailsBean.getInviteeStatus().getInviteeStatusCode() == 0) {

                mInviteCheckList.add(inviteDetailsBean);
            }
        }
    }
}
